<template>
  <el-dialog
    v-model="visible"
    title="📥 批量导入关键词"
    :width="600"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 第1步：下载模板 -->
    <!-- <div class="import-step">
      <h3 class="step-title">第1步: 下载模板</h3>
      <el-card class="step-card">
        <div class="template-info">
          <p class="template-desc">📄 Excel模板包含以下列:</p>
          <ul class="template-columns">
            <li>- 部门名称 (必填)</li>
            <li>- 关键词 (必填)</li>
            <li>- 权重 (必填, 0.1-1.0)</li>
            <li>- 备注 (可选)</li>
          </ul>
          <el-button
            type="primary"
            @click="downloadTemplate"
            class="download-btn"
          >
            <el-icon><download /></el-icon> 下载Excel模板
          </el-button>
        </div>
      </el-card>
    </div> -->

    <!-- 第2步：上传文件 -->
    <div class="import-step">
      <h3 class="step-title">第2步: 上传文件</h3>
      <el-card class="step-card">
        <div
          class="upload-area"
          :class="{ 'upload-area-active': isDragging }"
          @dragover.prevent="isDragging = true"
          @dragleave.prevent="isDragging = false"
          @drop.prevent="handleFileDrop"
        >
          <p class="upload-text">📂 拖拽文件到此处,或点击选择文件</p>
          <el-button
            type="default"
            class="select-file-btn"
            @click="triggerFileSelect"
          >
            点击选择文件
          </el-button>
          <input
            ref="fileInput"
            type="file"
            class="file-input"
            accept=".xlsx,.xls"
            @change="handleFileSelect"
          />
          <p class="file-info">支持格式: .xlsx, .xls</p>
          <p class="file-info">最大文件: 5MB</p>
        </div>

        <!-- 已选择文件显示 -->
        <div v-if="selectedFile" class="selected-file">
          <el-tag type="success" closable @close="clearSelectedFile">
            {{ selectedFile.name }}
          </el-tag>
        </div>
      </el-card>
    </div>

    <!-- 第3步：预览与确认 -->
    <div class="import-step" v-if="previewData.total > 0 || uploadError">
      <h3 class="step-title">第3步: 预览与确认</h3>
      <el-card class="step-card">
        <!-- 上传错误提示 -->
        <div v-if="uploadError" class="upload-error">
          <el-alert
            title="解析失败"
            :description="uploadError"
            type="error"
            show-icon
          />
        </div>

        <!-- 解析成功 -->
        <div v-else>
          <div class="parse-success">
            <span style="color: #4caf50; margin-right: 5px">✅</span>
            <span>解析成功! 共 {{ previewData.total }} 条数据</span>
          </div>

          <!-- 数据预览 -->
          <div class="data-preview">
            <p>预览前5条:</p>
            <el-table
              :data="previewData.preview"
              border
              size="small"
              :show-header="true"
              max-height="200"
            >
              <el-table-column prop="department" label="部门" />
              <el-table-column prop="keyword" label="关键词" />
              <el-table-column prop="weight" label="权重" />
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag
                    :type="
                      scope.row.status === '新增'
                        ? 'success'
                        : scope.row.status === '已存在'
                        ? 'warning'
                        : 'danger'
                    "
                  >
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 统计信息 -->
          <div class="stats-info">
            <p>统计:</p>
            <ul class="stats-list">
              <li>- 新增: {{ previewData.imported }}条</li>
              <li>- 已存在: {{ previewData.skipped }}条 (可选择覆盖或跳过)</li>
              <li>
                - 错误: {{ previewData.errors }}条
                <el-button
                  v-if="previewData.errors > 0"
                  type="text"
                  size="small"
                  @click="showErrorDetails = !showErrorDetails"
                  style="margin-left: 5px"
                >
                  {{ showErrorDetails ? "隐藏详情" : "查看详情" }}
                </el-button>
              </li>
            </ul>

            <!-- 错误详情 -->
            <div
              v-if="
                showErrorDetails &&
                previewData.errors > 0 &&
                previewData.error_details &&
                previewData.error_details.length > 0
              "
              class="error-details"
            >
              <el-table
                :data="previewData.error_details"
                border
                size="small"
                max-height="200"
              >
                <el-table-column
                  prop="row"
                  label="行号"
                  width="80"
                  align="center"
                />
                <el-table-column
                  prop="department"
                  label="部门"
                  min-width="120"
                />
                <el-table-column
                  prop="keyword"
                  label="关键词"
                  min-width="120"
                />
                <el-table-column
                  prop="error"
                  label="错误原因"
                  min-width="200"
                  show-overflow-tooltip
                />
              </el-table>
            </div>

            <!-- 重复处理策略 -->
            <div class="duplicate-strategy">
              <p>重复处理:</p>
              <el-radio-group v-model="duplicateStrategy">
                <el-radio label="skip">跳过</el-radio>
                <el-radio label="overwrite">覆盖</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        @click="handleConfirmImport"
        :disabled="!selectedFile || !!uploadError || previewData.imported <= 0"
      >
        确认导入 ({{ previewData.imported }}条)
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import { batchImportKeywords, downloadKeywordTemplate } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  departments: {
    type: Array,
    default: () => [],
  },
});

// 定义emits
const emit = defineEmits(["update:modelValue", "confirm-import", "close"]);

// 状态管理
const visible = ref(props.modelValue);
const isDragging = ref(false);
const selectedFile = ref<File | null>(null);
const uploadError = ref("");
const previewData = ref({
  total: 0,
  imported: 0,
  skipped: 0,
  errors: 0,
  preview: [],
  error_details: [],
});
const duplicateStrategy = ref("skip");
const showErrorDetails = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);

// 监听visible变化，同步到modelValue
watch(
  () => visible.value,
  (val) => {
    emit("update:modelValue", val);
  }
);

// 监听props.modelValue变化，同步到visible
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
  }
);

// 下载模板
const downloadTemplate = async () => {
  try {
    const loading = ElLoading.service({ text: "正在下载模板..." });
    const response = await downloadKeywordTemplate();

    // 处理文件下载
    const blob = new Blob([response as any], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "部门关键词导入模板.xlsx";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("模板下载成功");
    loading.close();
  } catch (error: any) {
    ElMessage.error(error?.message || "模板下载失败");
  }
};

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value?.click();
};

// 处理文件选择
const handleFileSelect = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    handleFile(target.files[0]);
  }
  // 重置input值，允许重复选择同一文件
  if (target) target.value = "";
};

// 处理文件拖拽
const handleFileDrop = (e: DragEvent) => {
  isDragging.value = false;
  if (e.dataTransfer && e.dataTransfer.files.length > 0) {
    handleFile(e.dataTransfer.files[0]);
  }
};

// 处理选中的文件
const handleFile = (file: File) => {
  // 验证文件类型
  const fileExt = file.name.split(".").pop()?.toLowerCase();
  if (!["xlsx", "xls"].includes(fileExt || "")) {
    ElMessage.error("请上传.xlsx或.xls格式的文件");
    return;
  }

  // 验证文件大小
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error("文件大小不能超过5MB");
    return;
  }

  // 保存选中的文件
  selectedFile.value = file;
  uploadError.value = "";

  // 解析文件并预览 (实际项目中可能需要先上传文件获取预览数据)
  previewFile(file);
};

// 解析文件并预览
const previewFile = async (file: File) => {
  try {
    const loading = ElLoading.service({ text: "正在解析文件..." });

    // 创建FormData用于预览
    const formData = new FormData();
    formData.append("file", file);
    formData.append("preview", "true"); // 标记为预览模式

    // 调用导入接口获取预览数据
    const result = await batchImportKeywords(formData);
    console.log(result, "resultresult");
    if (result?.data) {
      // 映射实际返回的数据结构
      const errorCount = result.data.error_count || result.data.errors || 0;
      const errorDetails = result.data.error_details || [];

      previewData.value = {
        total: result.data.total || 0,
        imported: result.data.success_count || result.data.imported || 0,
        skipped: result.data.skip_count || result.data.skipped || 0,
        errors: errorCount,
        preview: result.data.preview || [],
        error_details: errorDetails,
      };

      // 如果有错误，默认展开错误详情
      if (errorCount > 0 && errorDetails.length > 0) {
        showErrorDetails.value = true;
      }

      // 如果没有预览数据，但有错误详情，至少显示错误信息
      if (previewData.value.preview.length === 0 && errorDetails.length > 0) {
        // 可以尝试从错误详情中提取一些信息用于预览
        previewData.value.preview = errorDetails
          .slice(0, 5)
          .map((item: any) => ({
            department: item.department || "-",
            keyword: item.keyword || "-",
            weight: "-",
            status: "错误",
          }));
      }
    }

    loading.close();
  } catch (error: any) {
    uploadError.value = error?.message || "文件解析失败，请检查文件格式";
    previewData.value = {
      total: 0,
      imported: 0,
      skipped: 0,
      errors: 0,
      preview: [],
      error_details: [],
    };
  }
};

// 清除选中的文件
const clearSelectedFile = () => {
  selectedFile.value = null;
  uploadError.value = "";
  previewData.value = {
    total: 0,
    imported: 0,
    skipped: 0,
    errors: 0,
    preview: [],
    error_details: [],
  };
};

// 确认导入
const handleConfirmImport = async () => {
  if (!selectedFile.value) return;

  try {
    const loading = ElLoading.service({ text: "正在导入数据..." });

    // 创建FormData
    const formData = new FormData();
    formData.append("file", selectedFile.value);
    formData.append("duplicate_strategy", duplicateStrategy.value);

    // 调用导入接口
    const result = await batchImportKeywords(formData);

    ElMessage.success(result?.message || "批量导入成功");

    // 触发父组件的确认事件
    emit("confirm-import", result?.data);

    // 重置状态
    clearSelectedFile();
    visible.value = false;

    loading.close();
  } catch (error: any) {
    ElMessage.error(error?.message || "导入失败");
  }
};

// 关闭弹窗
const handleClose = () => {
  clearSelectedFile();
  emit("close");
  visible.value = false;
};
</script>

<style scoped lang="scss">
.import-step {
  margin-bottom: 20px;

  .step-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
    color: #333;
  }

  .step-card {
    border-radius: 6px;
    border: 1px solid #e5e7eb;
  }
}

.template-info {
  padding: 15px;

  .template-desc {
    margin: 0 0 10px 0;
    color: #666;
  }

  .template-columns {
    margin: 0 0 15px 0;
    padding-left: 20px;
    color: #666;

    li {
      margin-bottom: 5px;
    }
  }

  .download-btn {
    margin-top: 10px;
  }
}

.upload-area {
  padding: 30px;
  text-align: center;
  border: 2px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
  }

  .upload-text {
    margin: 0 0 15px 0;
    color: #666;
  }

  .select-file-btn {
    margin-bottom: 15px;
  }

  .file-info {
    margin: 5px 0;
    font-size: 12px;
    color: #999;
  }
}

.upload-area-active {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.file-input {
  display: none;
}

.selected-file {
  margin-top: 15px;
  text-align: center;
}

.parse-success {
  margin-bottom: 15px;
  padding: 5px 0;
  color: #4caf50;
  font-weight: 500;
  display: flex;
  align-items: center;

  el-icon {
    margin-right: 5px;
  }
}

.data-preview {
  margin-bottom: 15px;

  p {
    margin: 0 0 10px 0;
    font-weight: 500;
  }
}

.stats-info {
  p {
    margin: 0 0 10px 0;
    font-weight: 500;
  }

  .stats-list {
    margin: 0 0 15px 0;
    padding-left: 20px;

    li {
      margin-bottom: 5px;
      color: #666;
    }
  }

  .error-details {
    margin: 10px 0;
    padding: 10px;
    background-color: #fef2f2;
    border-radius: 4px;
  }

  .duplicate-strategy {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #eee;

    p {
      margin-bottom: 10px;
    }

    .el-radio-group {
      display: flex;
      gap: 20px;
    }
  }
}

.upload-error {
  margin-bottom: 10px;
}
</style>
